/**
 * Created by liaoxd on 2017/12/17.
 */
define([
    './custom/widgets/js/YuWorkflow_server.js',
    'pages/use/monitors/serviceMonitor/serviceMonitor.css'
], function (require, exports) {
    // page加载完成后调用ready方法
    exports.ready = function (hashCode, data, cite) {
        var size = yufp.frame.size();
        // 创建virtual Notice model
        var vm = yufp.custom.vue({
            el: cite.el,
            data: function () {
                return {
                    height: size.height - 80,
                    frequencyOptions: [{key: -1, value: '不自动刷新'}, {key: 10, value: '10秒'}, {
                        key: 20,
                        value: '20秒'
                    }, {key: 30, value: '30秒'}, {key: 60, value: '60秒'}],
                    serverType: ['S', 'C', 'A', 'N'], // 节点类型，注意有顺序的
                    tableData: [],
                    deployList: [],
                    timer: null,
                    timerDelay: -1,
                    dialogTableVisible: false,
                    anyscLoading: null,
                    deployStatus: [{key: 'ON', value: '启动'}, {key: 'OFF', value: '未启动'}],
                    serviceFormData: {},
                    currentTime: yufp.util.dateFormat(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
                    cellData: {},
                    baseData: [],
                    disabledTabPane: false,
                    tabsValue: 'xtree', // mxgraph | xtree
                    filterText: '',
                    rootId: '0',
                    stateOn: [],
                    stateOff: [],
                    stateStoping: [],
                    serviceMonitorLoading: null,
                    renderCustomContent: function (h, obj) {
                        var _this = this, data = obj.data, store = obj.store, node = obj.node;
                        var btnArray = [
                            {
                                name: '启动',
                                callback: function (e) {
                                    vm.overLayClickFn({tooltip: '启动'}, {data: data});
                                    vm.hiddenTreeBtn();
                                }
                            },
                            {
                                name: '停止',
                                callback: function () {
                                    vm.overLayClickFn({tooltip: '停止'}, {data: data});
                                    vm.hiddenTreeBtn();
                                }
                            },
                            {
                                name: '查看',
                                callback: function () {
                                    vm.celldblclickFn({data: data});
                                }
                            }
                        ];
                        return h('div', {class: 'tree-btn'}, btnArray.map(function (item) {
                            return h('span', {on: {click: item.callback}}, item.name)
                        }))
                    },
                    activeTabName: "basicInfo",
                    paramcfgDatas: [
                        {paramCode: '', paramName: '', paramValue: 0, paramValueC: 0}
                    ],
                    showParamInfo: true,
                    paramLoading: false,
                    infoLoading: false
                };
            },
            watch: {
                tabsValue: function (value, oldValue) {
                    this.disabledTabPane = true;
                    this.queryAllDeployInfo();
                },
                filterText: function (val) {
                    this.$refs.moduleTree && this.$refs.moduleTree.filter(val);
                }
            },
            created: function () {
                this.queryAllDeployInfo();
            },
            mounted() {
            },
            deactivated() {
            },
            activated() {
            },
            destroyed() {
                clearInterval(this.timer); //销毁自动刷新的定时器
                this.timer = null;
            },
            beforeDestory() {
            },
            methods: {
                queryAllDeployInfo: function () {
                    var _this = this;
                    yufp.service.request({
                        // url: backend.useService + '/plats/serverdeploy/queryList',
                        url: backend.useService + '/plats/serverdeploy/queryAllDeployInfo',
                        method: 'get',
                        data: null,
                        callback: function (code, message, response) {
                            if (response && response.data) {
                                var baseData = [];
                                if (response.data.length > 0) {
                                    baseData = response.data;
                                } else if (response.data.datas.length > 0) {
                                    baseData = response.data.datas;
                                }
                                _this.setBaseData(baseData);
                                // if (_this.tabsValue === 'mxgraph') {
                                //   _this.$refs.workflow.addStyle({
                                //     'S': '#cfb1ed',
                                //     'C': '#FFFFCF',
                                //     'A': '#B8C9EC',
                                //     'N': '#A5CB72'
                                //   });
                                //   var classification =  _this.getClassification( _this.baseData);
                                //   _this.$refs.workflow.loadData( _this.baseData, {
                                //     types: {
                                //       'S': 0,
                                //       'C': 1,
                                //       'A': 2,
                                //       'N': 3,
                                //     },
                                //     classification: classification
                                //   });
                                // }
                                setTimeout(function () {
                                    _this.disabledTabPane = false;
                                }, 600);
                                // 启动定时器刷新
                                _this.setRefreshTimer();
                                _this.btnUpdateWorkFlowFn();
                            }
                        }
                    });
                },
                setBaseData: function (baseData) {
                    var _this = this;
                    var treeData = _this.arrayToTree(baseData);
                    if (treeData.length > 0) {
                        _this.rootId = treeData[0].serverId;
                    }
                    baseData.forEach(function (item) {
                        item.state = item.state || '';
                        item.label = item.serverName + '（' + item.serverId + '）';
                        item.icon = 'server-type-' + item.serverType;
                        if (treeData[0].children) {
                            if (item.serverId === treeData[0].serverId) {
                                item.label = item.serverName + '（' + item.serverId + '）' + '（' + treeData[0].children.length + '）';
                            } else {
                                treeData[0].children.forEach(function (treeitem) {
                                    if (item.serverId === treeitem.serverId && treeitem.children) {
                                        item.label = item.serverName + '（' + item.serverId + '）' + '（' + treeitem.children.length + '）';
                                    }
                                })
                            }
                        }
                    })
                    _this.baseData = baseData;
                },
                arrayToTree: function (list) {
                    var arr = [];
                    var tmpMap = {};
                    list.forEach(function (item) {
                        tmpMap[item['serverId']] = item;
                    });
                    list.forEach(function (item) {
                        var key = tmpMap[item['parentId']];
                        if (key) {
                            if (!key['children']) {
                                key['children'] = [];
                            }
                            key['children'].push(item);
                        } else {
                            arr.push(item);
                        }
                    })
                    return arr;
                },
                filterNode: function (value, data) {
                    if (!value) {
                        return true;
                    }
                    if (value == 'ONczc') {//显示已启动的
                        if (this.filterText) {
                            return (data.state == 'ON' && (data.label.toLowerCase().indexOf(this.filterText.toLowerCase()) !== -1));
                        } else {
                            return data.state == 'ON';
                        }

                    } else if (value == 'OFFczc') {
                        if (this.filterText) {
                            return (data.state == 'OFF' && (data.label.toLowerCase().indexOf(this.filterText.toLowerCase()) !== -1));
                        } else {
                            return data.state == 'OFF';
                        }
                    } else {
                        return data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1;
                    }
                },
                nodeDbclick: function (data, node) {
                    this.celldblclickFn({data: data});
                },
                hiddenTreeBtn: function () {
                    document.querySelector('.serviceMonitor .el-tree .tree-btn').style.display = 'none';
                },
                // 显示loading
                showLoading: function () {
                    this.anyscLoading = this.$loading({fullscreen: true})
                },
                // 关闭loading
                closeLoading: function () {
                    this.anyscLoading.close();
                },
                // 接口数据转换成节点数据
                data2CellData: function () {
                    var nodeList = [], edgeList = [], width = this.size.width;
                    var typeList = options.classification;
                    for (var i = 0, l = data.length, d; i < l; i++) {
                        d = yufp.clone(data[i], {});
                        d['nodetype'] = d.serverType;
                        nodeList.push({
                            id: d.serverId,
                            value: d.serverName,
                            x: (width - 200) / 2 + 200 * typeList[d.serverType],
                            y: 30 + 75 * options.types[d.serverType],
                            width: 160,
                            height: 56,
                            style: 'custom-style-' + d.serverType,
                            relative: false,
                            nodetype: d.serverType,
                            data: d
                        })
                        if (d.parentId && d.parentId !== '0') {
                            edgeList.push({
                                id: d.parentId + '-' + d.serverId,
                                // value: 'edge-' + i,
                                value: '',
                                source: d.parentId,
                                target: d.serverId
                            });
                        }
                    }
                },
                // 设置刷新时钟timer
                setRefreshTimer: function () {
                    var _this = this;
                    _this.timer && window.clearInterval(_this.timer);
                    var delay = parseInt(_this.timerDelay);
                    // 去掉不刷新操作
                    if (delay > 0) {
                        _this.timer = setInterval(function () {
                            _this.btnRefreshWorkFlowFn();
                        }, delay * 1000)
                    }
                },
                // 刷新按钮事件，刷新流程图状态
                btnRefreshWorkFlowFn: function () {
                    this.btnUpdateWorkFlowFn();
                },
                showServiceMonitorLoading: function () {
                    this.serviceMonitorLoading = this.$loading({
                        target: '.serviceMonitor',
                        fullscreen: 'false',
                        text: '加载中'
                    });
                },
                closeServiceMonitorLoading: function () {
                    this.serviceMonitorLoading && this.serviceMonitorLoading.close();
                },
                // 全部启动按钮操作
                btnStartAllWorkFlowFn: function () {
                    var _this = this;
                    _this.showServiceMonitorLoading();
                    yufp.service.request({
                        url: backend.useService + '/monitor/serviceMonitor/turnOnAllModule',
                        method: 'get',
                        data: null,
                        callback: function (code, message, response) {
                            _this.closeServiceMonitorLoading();
                            if (response && response.data && response.data.data) {
                                var baseData = response.data.data;
                                _this.setBaseData(baseData);
                                _this.getStatusData();
                                _this.$message('操作成功,请刷新监控查看');
                            } else {
                                _this.$message('操作失败: ' + message);
                            }
                        }
                    });
                },
                // 全部停止按钮操作
                btnStopAllWorkFlowFn: function () {
                    var _this = this;
                    _this.showServiceMonitorLoading();
                    yufp.service.request({
                        url: backend.useService + '/monitor/serviceMonitor/turnOffAllModule',
                        method: 'get',
                        data: null,
                        callback: function (code, message, response) {
                            _this.closeServiceMonitorLoading();
                            if (response && response.data) {
                                var baseData = response.data.data;
                                _this.setBaseData(baseData);
                                _this.getStatusData();
                                _this.$message('操作成功,请刷新监控查看');
                            } else {
                                _this.$message('操作失败: ' + message);
                            }
                        }
                    });
                },
                overLayClickFn: function (overlay, cell) {
                    if (overlay.tooltip === '启动') {
                        this.onOneModule(cell.data)
                    }
                    if (overlay.tooltip === '停止') {
                        this.offOneModule(cell.data)
                    }
                },
                // 单节点启动
                onOneModule: function (data) {
                    var _this = this;
                    _this.showServiceMonitorLoading();
                    yufp.service.request({
                        url: backend.useService + '/monitor/serviceMonitor/turnOnOneModule',
                        method: 'get',
                        data: {
                            serverId: data.serverId,
                            serverType: data.serverType
                        },
                        callback: function (code, message, response) {
                            _this.closeServiceMonitorLoading();
                            if (response && response.data) {
                                _this.getStatusData();
                                _this.btnUpdateWorkFlowFn();
                                _this.$message('启动成功');
                            } else {
                                _this.$message('启动失败: ' + message);
                            }
                        }
                    });
                },
                // 单节点停止
                offOneModule: function (data) {
                    var _this = this;
                    _this.showServiceMonitorLoading();
                    yufp.service.request({
                        url: backend.useService + '/monitor/serviceMonitor/turnOffOneModule',
                        method: 'get',
                        data: {
                            serverId: data.serverId,
                            serverType: data.serverType
                        },
                        callback: function (code, message, response) {
                            _this.closeServiceMonitorLoading();
                            if (response && response.data) {
                                _this.getStatusData();
                                _this.btnUpdateWorkFlowFn();
                                _this.$message('停止成功');
                            } else {
                                _this.$message('停止失败: ' + message);
                            }
                        }
                    });
                },
                // 单IP启动
                serverStartFn: function () {
                    var _this = this;
                    var selections = _this.$refs.deployTable.selections;
                    if (selections.length > 0) {
                        var row = selections[0];
                        // _this.showServiceMonitorLoading();
                        _this.infoLoading = true;
                        yufp.service.request({
                            url: backend.useService + '/monitor/serviceMonitor/turnOnSingleDeploy',
                            method: 'get',
                            data: {
                                serverId: _this.cellData.serverId,
                                serverType: _this.cellData.serverType,
                                location: row.location
                            },
                            callback: function (code, message, response) {
                                // _this.closeServiceMonitorLoading();
                                _this.infoLoading = false;
                                if (response && response.data) {
                                    _this.getStatusData();
                                    _this.btnUpdateWorkFlowFn();
                                    _this.$message('启动成功');
                                } else {
                                    _this.$message('启动失败: ' + message);
                                }
                            }
                        });
                    } else {
                        _this.$message({message: "请选择一个ip操作", type: "warning"});
                    }
                },
                // 单IP停止
                serverStopFn: function () {
                    var _this = this;
                    var selections = _this.$refs.deployTable.selections;
                    if (selections.length > 0) {
                        var row = selections[0];
                        // _this.showServiceMonitorLoading();
                        _this.infoLoading = true;
                        yufp.service.request({
                            url: backend.useService + '/monitor/serviceMonitor/turnOffSingleDeploy',
                            method: 'get',
                            data: {
                                serverId: _this.cellData.serverId,
                                serverType: _this.cellData.serverType,
                                location: row.location
                            },
                            callback: function (code, message, response) {
                                // _this.closeServiceMonitorLoading();
                                _this.infoLoading = false;
                                if (response && response.data) {
                                    _this.getStatusData();
                                    _this.btnUpdateWorkFlowFn();
                                    _this.$message('停止成功');
                                } else {
                                    _this.$message('停止失败: ' + message);
                                }
                            }
                        });
                    } else {
                        _this.$message({message: "请选择一个ip操作", type: "warning"});
                    }
                },
                // 获取新的流程图状态数据
                btnUpdateWorkFlowFn: function () {
                    var _this = this;
                    _this.showServiceMonitorLoading();
                    yufp.service.request({
                        url: backend.useService + '/monitor/serviceMonitor/queryAllList',
                        method: 'get',
                        data: null,
                        callback: function (code, message, response) {
                            _this.closeServiceMonitorLoading();
                            if (response && response.data) {
                                var baseData = [];
                                if (response.data.length > 0) {
                                    baseData = response.data;
                                } else if (response.data.data.length > 0) {
                                    baseData = response.data.data;
                                }
                                _this.setBaseData(baseData);
                                _this.getStatusData();
                            }
                            _this.currentTime = yufp.util.dateFormat(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
                            if (yufp.frame.getTab().title === '服务监控') {
                                _this.$message('刷新成功');
                            }
                        }
                    });
                },
                // 遍历数据更新流程图节点状态
                getStatusData: function () {
                    var _this = this;
                    // 从新从接口中获取数据,然后根据数据值判断状态
                    _this.stateOn = [];
                    _this.stateOff = [];
                    _this.stateStoping = [];
                    this.baseData.forEach(function (item) {
                        item.state = 'ON';
                        // 判断节点数据后更新状态
                        if (item.deployList) {
                            var tmpStatus = 'OFF';
                            item.deployList.forEach(function (deploy) {
                                if (deploy.status == 'OFF') {
                                    item.state = 'OFF';
                                } else {
                                    tmpStatus = 'ON';
                                }
                            })
                            if (item.state == 'ON') {
                                _this.stateOn.push(item);
                            } else if (item.state == 'OFF') {
                                if (tmpStatus == 'ON') {
                                    item.state = 'stoping';
                                    _this.stateStoping.push(item);
                                } else {
                                    _this.stateOff.push(item);
                                }
                            }
                        }
                        if (_this.cellData && item.serverId == _this.cellData.serverId) {
                            _this.cellData = item;
                            _this.deployList = item.deployList;
                        }
                        item.icon = 'server-type-' + item.serverType + ' ' + item.state;
                    })
                    // 刷新流程图
                    if (this.$refs.workflow) {
                        this.$refs.workflow.updateWorkStates(this.baseData);
                    }
                },
                // 刷新频率下拉框选择改变事件
                frequencyChangeFn: function () {
                    this.setRefreshTimer();
                },
                /**
                 * @description 获取分类信息
                 * @param {Array<Object>} list 数据列表
                 */
                getClassification: function (list) {
                    if (list && list.length > 0) {
                        var typeList = {};
                        for (var i = 0, l = list.length; i < l; i++) {
                            typeList[list[i].serverType] = (typeList[list[i].serverType] || 0) + 1;
                        }
                        return typeList;
                    }
                    return null;
                },
                showStatus: function (type) {
                    this.$refs.moduleTree && this.$refs.moduleTree.filter(type + 'czc');
                },
                // 隐藏弹窗
                hidePopWindow: function () {
                    this.dialogTableVisible = false;
                    this.$refs.serviceForm.resetFields();
                },
                // 显示弹窗
                showDialog: function () {
                    this.activeTabName = "basicInfo";
                    this.dialogTableVisible = true;
                },
                // 节点双击事件
                celldblclickFn: function (cell) {
                    if (cell.vertex || this.tabsValue === 'xtree') {
                        this.currentVertex = cell;
                        this.showDialog();
                        var data = cell.data;
                        var _this = this;
                        _this.infoLoading = true;
                        if (data.serverType === 'S') {
                            _this.showParamInfo = false;
                        } else {
                            _this.showParamInfo = true;
                        }
                        // data数据包中已经包含了status数据，无需再做匹配，且匹配过程会导致状态异常
                        // _this.baseData.forEach(item => {
                        //   if (item.serverId === data.serverId) {
                        //     item.deployList.forEach(deploy1 => {
                        //       data.deployList.forEach(deploy2 => {
                        //         if (deploy1.serverId === deploy2.serverId) {
                        //           deploy2.status = deploy1.status;
                        //         }
                        //       })
                        //     })
                        //   }
                        // })
                        this.cellData = data;
                        if (data.serverType === 'S') {
                            _this.infoLoading = false;
                        }
                        this.$nextTick(function () {
                            _this.$refs.serviceForm.resetFields();
                            _this.$refs.serviceForm.setFormData(data);
                            if (data.serverType !== 'S') {
                                _this.queryWftServerParam(data);
                            }
                            _this.deployList = data.deployList || [];
                        })
                    }
                },
                queryWftServerParam: function (data) {
                    var _this = this;
                    yufp.service.request({
                        method: 'GET',
                        url: "/api/use/monitor/serviceMonitor/queryParams",
                        data: {
                            serverId: data.serverId,
                            serverType: data.serverType
                        },
                        callback: function (code, message, response) {
                            if (response.code != 0) {
                                _this.$message(response.message);
                            } else {
                                _this.paramcfgDatas.splice(0);
                                _this.paramcfgDatas.push({
                                    serverId: data.serverId,
                                    serverName: data.serverName,
                                    paramValue: response.data.paramValue,
                                    paramValueC: response.data.paramValueC
                                });
                            }
                            _this.infoLoading = false;
                        }
                    });
                },
                saveParams: function () {
                    var _this = this;
                    _this.paramLoading = true;
                    if (_this.paramcfgDatas[0].paramValueC % 1 === 0) {
                        yufp.service.request({
                            method: 'GET',
                            url: "/api/use/monitor/serviceMonitor/setParams",
                            data: {
                                serverId: _this.cellData.serverId,
                                serverType: _this.cellData.serverType,
                                remark: _this.paramcfgDatas[0].paramValueC
                            },
                            callback: function (code, message, response) {
                                _this.paramLoading = false;
                                if (response.code != 0) {
                                    _this.$message({message: response.message, type: "error"});
                                } else {
                                    _this.$message("调整成功");
                                    _this.hidePopWindow();
                                }
                            }
                        });
                    } else {
                        _this.$message({message: "请输入数字", type: "warning"});
                    }
                }
            }
        });
    };
    // 消息处理
    exports.onmessage = function (type, message) {
    };
    // page销毁时触发destroy方法
    exports.destroy = function (id, cite) {
    };
});
